package com.tanhua.dubbo.api.impl.mongo;

import com.tanhua.domain.mongo.Visitors;
import com.tanhua.dubbo.api.mongo.VisitorsApi;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@Service
public class VisitorsApiImpl implements VisitorsApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 查找最近访客
     * @param userId  当前登陆者
     * @param count  查找总记录数
     * @param lastTime  上一次访问时间
     * @return
     */
    @Override
    public List<Visitors> queryVisitors(Long userId, int count, Long lastTime) {
        Query query = null;
        if(lastTime==null){
            //没有上一次访问时间
            query = new Query(Criteria.where("userId").is(userId));
        }else{
            //有上一次访问时间
            query = new Query(Criteria.where("userId").is(userId).and("date").gt(lastTime));
        }
        query.with(Sort.by(Sort.Order.desc("date")));
        query.limit(count);

        List<Visitors> visitorsList = mongoTemplate.find(query, Visitors.class);
        return visitorsList;
    }
}
